<?php
namespace app\beautiful\controller\admin\partner;
use app\BaseController;
use app\common\logic\DataLogic;
use app\beautiful\logic\PartnerLogic;
use app\beautiful\model\member\MemberBalanceModel;
use app\beautiful\model\member\MemberIntegralModel;
use app\beautiful\model\member\MemberModel;
use app\beautiful\model\partner\PartnerCommissionModel;
use app\beautiful\model\partner\PartnerSettingModel;
use app\beautiful\model\partner\PartnerWithdrawModel;
use app\beautiful\model\PartnerModel;

class Partner extends BaseController{
    protected $name='合伙人';

    public function index()
    {
        $type=$this->request->param('type/d',1);
        $mobile=$this->request->param('mobile');
        $status=$this->request->param('status/d',1);
        $where=[
            ['shop_id','=',$this->request->shopId],
            ['is_delete','=',0],
            ['role_id','=',$type]
        ];
        if(!empty($mobile)) $where[]=['mobile','=',$mobile];
        if($type==1) $where[]=['status','=',$status];

        $partner_model= new PartnerModel();
        
        $order=['add_time'=>'desc'];
        $field="*";
        $append=['add_time_format'];
        if($type==1) $append=['is_expire','add_time_format'];
        $return = DataLogic::getDataList($partner_model,$where,$order,$field,$this->request->limit,$this->request->page,$append);
        return $this->success($return);
    }

    public function show()
    {
        $return=[];
        //获取股金数据
        if(null === $partner_setting = PartnerSettingModel::where('shop_id',$this->request->shopId)->find()){
            return $this->error('您还未设置合伙设置，请先设置');
        }
        $return['dividend_ratio_data']=$partner_setting->dividend_ratio_data;

        $partner_id = $this->request->param('partner_id/d',0);
        if($partner_id==0) return $this->success($return);

        if(null === $partner = PartnerModel::find($partner_id)) return $this->error($this->name.'不存在');
        if($partner->shop_id != $this->request->shopId) return $this->error($this->name.'不存在');
        if($partner->is_delete == 1) return $this->error($this->name.'不存在');

        $detail=[
            'name'=>$partner->name,
            'mobile'=>$partner->mobile,
            'custom_name'=>$partner->custom_name,
            'custom_rate'=>$partner->custom_rate,
            'custom_second_rate'=>$partner->custom_second_rate,
            'expire_time'=>$partner->expire_time,
        ];
        $return['detail']=$detail;

        return $this->success($return);
    }

    public function detail()
    {
        $partner_id = $this->request->param('partner_id/d',0);
        $role_id=$this->request->param('role_id/d',0);
        if(!in_array($role_id,[1,2,3,4])) return $this->error('参数错误');
        if(null === $partner = PartnerModel::find($partner_id)) return $this->error($this->name.'不存在');
        if($partner->shop_id != $this->request->shopId) return $this->error($this->name.'不存在');
        if($partner->is_delete == 1) return $this->error($this->name.'不存在');
        if($partner->role_id != $role_id) return $this->error($this->name.'不存在');
        $partner->append(['role_means']);

        if(null === $pmember = MemberModel::where([
                ['shop_id','=',$this->request->shopId],
                ['mobile','=',$partner->mobile]
            ])->find()){
            return $this->error($this->name.'暂未激活');
        }

        $customer_num=MemberModel::where([
            ['shop_id','=',$this->request->shopId],
            ['pid','=',$pmember->member_id]
        ])->count() ?? 0;

        $detail=[
            'name'=>$partner->name,
            'mobile'=>$partner->mobile,
            'expire_time'=>$partner->expire_time,
            'share_capital'=>$partner->share_capital,
            'profit_rate'=>$this->getShareRate($partner->share_capital),
            'second_profit_rate'=>$this->getSecondShareRate($partner->share_capital),
            'profit'=>$partner->profit,
            'withdrawable_profit'=>$partner->withdrawable_profit,
            'role_means'=>$partner->role_means,
            'customer_num'=>$customer_num,
            'custom_name'=>$partner->custom_name,
            'custom_rate'=>$partner->custom_rate,
            'custom_second_rate'=>$partner->custom_second_rate,
        ];

        if($role_id==2){
            $detail['monetary'] = PartnerCommissionModel::where([
                ['shop_id','=',$this->request->shopId],
                ['partner_id','=', $partner->partner_id]
            ])->sum('monetary');
            $detail['commission'] = PartnerCommissionModel::where([
                ['shop_id','=',$this->request->shopId],
                ['partner_id','=', $partner->partner_id]
            ])->sum('commission');
        }
        $return['detail']=$detail;

        return $this->success($return);
    }

    public function getPartnerIncomeList()
    {
        $partner_id = $this->request->param('partner_id/d',0);
        $role_id=$this->request->param('role_id/d',0);
        $month=$this->request->param('month');
        if(!in_array($role_id,[1,2,3,4])) return $this->error('参数错误');
        if(null === $partner = PartnerModel::find($partner_id)) return $this->error($this->name.'不存在');
        if($partner->shop_id != $this->request->shopId) return $this->error($this->name.'不存在');
        if($partner->is_delete == 1) return $this->error($this->name.'不存在');
        if($partner->role_id != $role_id) return $this->error($this->name.'不存在');

        $where=[
            ['shop_id','=',$this->request->shopId],
            ['partner_id','=',$partner_id],
        ];
        if(!empty($month)) $where[]=['month','=',$month];

        $commission_model= new PartnerCommissionModel();
        if($role_id==3){
            $commission_model=$commission_model->with(['member']);
        }
        $order=['add_time'=>'desc'];
        $field="*";
        $append=['add_time_format'];

        $return = DataLogic::getDataList($commission_model,$where,$order,$field,$this->request->limit,$this->request->page,$append);
        if($return['list']) {
            $arr = [
                1 => '一级提成',
                2 => '二级提成',
            ];
            foreach($return['list'] as $key => $val) {
                $return['list'][$key]['level'] = $arr[$val['level']];
            }
        }

        return $this->success($return);
    }

    public function getPartnerCustomerList()
    {
        $partner_id = $this->request->param('partner_id/d',0);
        $role_id=$this->request->param('role_id/d',0);
        if(!in_array($role_id,[1,2,3,4])) return $this->error('参数错误');
        if(null === $partner = PartnerModel::find($partner_id)) return $this->error($this->name.'不存在');
        if($partner->shop_id != $this->request->shopId) return $this->error($this->name.'不存在');
        if($partner->is_delete == 1) return $this->error($this->name.'不存在');
        if($partner->role_id != $role_id) return $this->error($this->name.'不存在');

        if(null === $pmember = MemberModel::where([
                ['shop_id','=',$this->request->shopId],
                ['mobile','=',$partner->mobile]
            ])->find()){
            return $this->error($this->name.'不存在');
        }

        $where=[
            ['shop_id','=',$this->request->shopId],
            ['pid','=',$pmember->member_id],
        ];
        $memberModel=new MemberModel();
        $order=['add_time'=>'desc'];
        $append=['add_time_format'];
        $field='member_id,nick_name,face,mobile,pid,add_time';
        $data=DataLogic::getDataList($memberModel,$where,$order,$field,$this->request->limit,$this->request->page,$append);
        
        //处理数据
        $lists=$data['list'];
        if(empty(!$lists)){
            $PartnerCommissionModel = new PartnerCommissionModel();
            $memberIds = $moneys= [];
            $subordinate = [];
            foreach($lists as $val){
                $memberIds[$val['member_id']] = $val['member_id'];
                $subordinate_money = $PartnerCommissionModel->getSubordinateMonetarySumByPartnerId($val['member_id'],$this->request->shopId);
                $subordinate[$val['member_id']] = $subordinate_money > 0 ? $subordinate_money : 0;
            }
            // var_dump($subordinate);exit;
            if(!empty($memberIds)){
                $moneys =  $PartnerCommissionModel->getMonetarySumByPartnerId($memberIds);
            }
            
            foreach ($lists as $k => $list){
                $lists[$k]['money']=$moneys[$list['member_id']] ?? 0;
                $lists[$k]['subordinate']=$subordinate[$list['member_id']] ?? 0;
            }
        }
        $data['list']=$lists;
        return $this->success($data);
    }

    public function bindMember()
    {
        $partner_id = $this->request->param('partner_id/d',0);
        $role_id=$this->request->param('role_id/d',0);
        if(!in_array($role_id,[1,2,3,4])) return $this->error('参数错误');
        $mobile=$this->request->param('mobile');
        if(empty($mobile)) return $this->error('请输入手机号');
        if(!is_mobile($mobile)) return $this->error('请输入正确的手机号');

        if(null === $partner = PartnerModel::find($partner_id)) return $this->error($this->name.'不存在');
        if($partner->shop_id != $this->request->shopId) return $this->error($this->name.'不存在');
        if($partner->is_delete == 1) return $this->error($this->name.'不存在');
        if($partner->role_id != $role_id) return $this->error($this->name.'不存在');

        if(null === $pmember = MemberModel::where([
                ['shop_id','=',$this->request->shopId],
                ['mobile','=',$partner->mobile]
            ])->find()){
            return $this->error($this->name.'不存在');
        }

        if(null !== MemberModel::where([
                ['mobile','=',$mobile],
                ['shop_id','=',$this->request->shopId],
            ])->find()){
            return $this->error('该手机号已经注册了，请重新输入');
        }

        $member = new MemberModel();
        $member->mobile=$mobile;
        $member->shop_id = $this->request->shopId;
        $member->nick_name = '未设置'; //防止有特殊字的用户
        $member->save();

        $partner_logic= new PartnerLogic($this->request->shopId);
        $res= $partner_logic->bindPartner($member->member_id,$pmember->member_id,true);
        return $this->success('添加成功');

    }

    public function getPartnerDetailWithdrawList()
    {
        $partner_id = $this->request->param('partner_id/d',0);
        $role_id=$this->request->param('role_id/d',0);
        if(!in_array($role_id,[1,2,3,4])) return $this->error('参数错误');

        if(null === $partner = PartnerModel::find($partner_id)) return $this->error($this->name.'不存在');
        if($partner->shop_id != $this->request->shopId) return $this->error($this->name.'不存在');
        if($partner->is_delete == 1) return $this->error($this->name.'不存在');
//        if($partner->role_id != $role_id) return $this->error($this->name.'不存在');

        $where=[
            ['shop_id','=',$this->request->shopId],
            ['partner_id','=',$partner_id]
        ];
        $partner_withdraw_model= new PartnerWithdrawModel();
        $order=['add_time'=>'desc'];
        $field='*';
        $append=['add_time_format','status_means'];
        $return= DataLogic::getDataList($partner_withdraw_model,$where,$order,$field,$this->request->limit,$this->request->page,$append);

        return $this->success($return);
    }

    protected function getShareRate($share_capital)
    {
        $commissionRate = 0;
        if(null === $partner_setting = PartnerSettingModel::where('shop_id',$this->request->shopId)->find()){
            return $commissionRate;
        }

        if(empty($partner_setting->dividend_ratio_data)) return $commissionRate;

        foreach($partner_setting->dividend_ratio_data as $val){
            if($val['share_capital'] <= $share_capital && $val['dividend_ratio'] >= $commissionRate){
                $commissionRate =  $val['dividend_ratio'];
            }
        }

        if($commissionRate <= 0 || $commissionRate >= 100) return 0;

        return $commissionRate;
    }
    
    protected function getSecondShareRate($share_capital)
    {
        $commissionRate = 0;
        if(null === $partner_setting = PartnerSettingModel::where('shop_id',$this->request->shopId)->find()){
            return $commissionRate;
        }

        if(empty($partner_setting->dividend_ratio_data)) return $commissionRate;
        foreach($partner_setting->dividend_ratio_data as $val){
            if($val['share_capital'] <= $share_capital){
                $commissionRate =  $val['second_ratio'];
            }
        }
        if($commissionRate <= 0 || $commissionRate >= 100) return 0;

        return $commissionRate;
    }

    public function save()
    {
        $type=$this->request->param('type/d');
        $partner_id = $this->request->param('partner_id/d',0);
        $name=$this->request->param('name');
        $mobile=$this->request->param('mobile');
        $custom_name=$this->request->param('custom_name');
        $custom_rate=$this->request->param('custom_rate/f',0);
        $custom_second_rate=$this->request->param('custom_second_rate/f',0);
        $expire_time=$this->request->param('expire_time');
        $index= $this->request->param('index/d',-1);

        if(null === $partner_setting = PartnerSettingModel::where('shop_id',$this->request->shopId)->find()){
            return $this->error('您还未设置合伙设置，请先设置');
        }

        //判断传来的参数
        if(!in_array($type,[1,2,3,4])) return $this->error('参数错误');
        if(empty($name)) return $this->error('请输入合伙人姓名');
        if(empty($mobile) || !is_mobile($mobile)) return $this->error('请输入合伙人手机号');
        if(in_array($type,[1,4])){
            if(empty($expire_time)) return $this->error('请选择过期时间');
            if(false === $expire_time_unix = strtotime($expire_time)) return $this->error('请选择正确的过期时间');
        }
        if($type==1){
            if($index<0) return $this->error('请选择股金');
            $dividend_ratio_data=$partner_setting->dividend_ratio_data;
            if(!isset($dividend_ratio_data[$index])) return $this->error('未找到股金，请重新选择');
            $share_capital=$dividend_ratio_data[$index]['share_capital'];
        }
        if($type==4){
            if(empty($custom_name)) return $this->error('请输入自定义名称');
            if(empty($custom_rate) || $custom_rate <=0 ||$custom_rate>100) return $this->error('请输入一级佣金比例，且不能小于0或者大于100');
            if(empty($custom_second_rate) || $custom_second_rate <=0 ||$custom_second_rate>100) return $this->error('请输入二级佣金比例，且不能小于0或者大于100');
        }

        if($partner_id != 0){
            if(null === $partner = PartnerModel::find($partner_id)) return $this->error($this->name.'不存在');
            if($partner->shop_id != $this->request->shopId) return $this->error($this->name.'不存在');
            if($partner->is_delete == 1) return $this->error($this->name.'不存在');
            if($partner->role_id != $type) return $this->error($this->name.'不存在');
            //判断是否已经存在
            if($partner->mobile != $mobile){
                if(null !== PartnerModel::where([
                        ['shop_id','=',$this->request->shopId],
                        ['is_delete','=',0],
                        ['mobile','=',$mobile],
                    ])->find()){
                    return $this->error('这个手机号已经存在合伙人了');
                }
            }

        }else{
            $partner = new PartnerModel();
            $partner->shop_id = $this->request->shopId;
            $partner->role_id=$type;
            if(null !== PartnerModel::where([
                    ['shop_id','=',$this->request->shopId],
                    ['is_delete','=',0],
                    ['mobile','=',$mobile],
                ])->find()){
                return $this->error('这个手机号已经存在合伙人了');
            }
        }

        $partner->name=$name;
        $partner->mobile=$mobile;
        if(in_array($type,[1,4])){
            $partner->expire_time=$expire_time;
        }
        if($type==1){
            $partner->share_capital=$share_capital;
        }
        if($type==4){
            $partner->custom_name=$custom_name;
            $partner->custom_rate=$custom_rate;
            $partner->custom_second_rate=$custom_second_rate;
        }
        $partner->save();

        if(null ===  MemberModel::where([
                ['shop_id','=',$this->request->shopId],
                ['mobile','=',$partner->mobile]
            ])->find()){
            $member = new MemberModel();
            $member->mobile=$mobile;
            $member->shop_id = $this->request->shopId;
            $member->nick_name = '未设置'; //防止有特殊字的用户
            $member->save();
        }

        return $this->success('保存成功');

    }

    public function delay()
    {
        $partner_id = $this->request->param('partner_id/d',0);
        $expire_time=$this->request->param('expire_time');

        if(empty($expire_time)) return $this->error('请选择过期时间');
        if(false === $expire_time_unix = strtotime($expire_time)) return $this->error('请选择正确的过期时间');
        if(null === $partner = PartnerModel::find($partner_id)) return $this->error($this->name.'不存在');
        if($partner->shop_id != $this->request->shopId) return $this->error($this->name.'不存在');
        if($partner->is_delete == 1) return $this->error($this->name.'不存在');
        if($partner->role_id != 1) return $this->error($this->name.'不存在');
        if($partner->status == -1 ) return $this->error($this->name.'已经退股了,无法删除');

        $partner->expire_time = $expire_time;
        $partner->save();
        return $this->success('操作成功');
    }
    

    public function withdrawal()
    {
        $partner_id = $this->request->param('partner_id/d',0);
        if(null === $partner = PartnerModel::find($partner_id)) return $this->error($this->name.'不存在');
        if($partner->shop_id != $this->request->shopId) return $this->error($this->name.'不存在');
        if($partner->is_delete == 1) return $this->error($this->name.'不存在');
        if(!in_array($partner->role_id,[1,4])) return $this->error($this->name.'不存在');
        if($partner->status == -1 ) return $this->error($this->name.'已经退股了，请勿重复操作');
        //其他判断，待补充

        $partner->status=-1;
        $partner->save();
        return $this->success('操作成功');
    }

    public function del()
    {
        $partner_id = $this->request->param('partner_id/d',0);
        if(null === $partner = PartnerModel::find($partner_id)) return $this->error($this->name.'不存在');
        if($partner->shop_id != $this->request->shopId) return $this->error($this->name.'不存在');
        if($partner->is_delete == 1) return $this->error($this->name.'不存在');
        if(in_array($partner->role_id,[1,4])){
            if($partner->status != -1) return $this->error('还未退股，无法删除');
        }
        //其他判断，待补充

        $partner->is_delete=1;
        $partner->save();
        return $this->success('操作成功');
    }
}
